import { t } from 'i18next'
import { TvWallMemberItemEntity } from '@/api/manager/tvwall/interface'
import { DropData, makeMtEntityParam } from '@/api/manager/type'
import Alert from '@/components/Alert'
import { DragDropContextProvider, Droppable } from '@/plugins/dnd'
import { FC, useEffect, useState } from 'react'
import shallow from 'zustand/shallow'
import { BoxSetting } from '../BoxItem'
import { chnInfoEntity } from '../interface'
import { useTvWallStore } from '../store'
import { handleGetEeeorCodeText, isEqualMtchnids } from '../translator'
import { AddIcon, StyledNormalWrap, Wrap } from './style'
import { useMccStore } from '@/pages/manager/store'
interface ContentProps {
	/**数据源*/
	boxInfo: TvWallMemberItemEntity
	/**数组源位置 */
	index: number
}
export const Content: FC<ContentProps> = ({ boxInfo, index }) => {
	const {
		mode,
		convertMsg,
		boxDetailVOsSourceErrorCode,
		update,
		boxDetailVOsSource,
		getRate,
		style_map,
		correct_style,
		removeStreamDom,
		getMTChnInfo,
		streamDomData,
		show_mt_name,
		changeTVWallChannel,
		removeErrorMark,
	} = useTvWallStore(
		(state) => ({
			update: state.update,
			mode: state.mode,
			convertMsg: state.convertMsg,
			boxDetailVOsSourceErrorCode: state.boxDetailVOsSourceErrorCode,
			boxDetailVOsSource: state.boxDetailVOsSource,
			getRate: state.getRate,
			style_map: state.style_map,
			correct_style: state.correct_style,
			removeStreamDom: state.removeStreamDom,
			getMTChnInfo: state.getMTChnInfo,
			streamDomData: state.streamDomData,
			show_mt_name: state.show_mt_name,
			changeTVWallChannel: state.changeTVWallChannel,
			removeErrorMark: state.removeErrorMark,
		}),
		shallow
	)
	const { meetingType } = useMccStore(
		(state) => ({
			meetingType: state.mccInfo.meetingType,
		}),
		shallow
	)
	let _rate = getRate('mcc') /**盒子缩放码率 */
	let _style_position = style_map[correct_style].positions /**当前电视墙风格位置信息 */
	const { box_x, box_y, box_width, box_height } = _style_position[index] /**盒子位置信息*/
	/**上下左右的偏移量 */
	const _left = box_x * _rate
	const _right = box_y * _rate
	const _width = box_width * _rate
	const _height = box_height * _rate
	const [is_show_setting, setIsShowSetting] = useState(false) /**是否展示设置 */
	const [err_text, setErrorText] = useState('') /**错误文本 */
	const [err_text_show, setErrorTextShow] = useState(false) /**错误展示 */
	const [stream_position, setStreamPosition] = useState('') /**多流位置 */
	const [active, setActive] = useState(false) /**是否展示设置 */
	useEffect(() => {
		if (boxInfo.member_type === 1 && boxInfo.mt_id && boxInfo.stream === 1) {
			getMTChnInfo(boxInfo, (list: Array<chnInfoEntity>) => {
				let _name = ''
				let mtchnids = list.map((x) => x.v_snd_chn_id).sort((a: number, b: number) => a - b)
				if (boxInfo.mt_chn_id === mtchnids[0]) {
					_name = t('（左）')
				} else if (boxInfo.mt_chn_id === mtchnids[1]) {
					_name = t('（中）')
				} else if (boxInfo.mt_chn_id === mtchnids[2]) {
					_name = t('（右）')
				}
				setStreamPosition(_name)
			})
		}
	}, [boxInfo])
	/**展示错误码 */
	const handleShowErrorMark = () => {
		let _result = boxDetailVOsSourceErrorCode || {}
		let _key = boxInfo.hdu_id || ''
		const _error_code = _result[_key]
		const _err_text = handleGetEeeorCodeText(Number(_error_code) || 0)
		setErrorText(_err_text)
		setErrorTextShow(true)
	}
	/**移除错误码 */
	const handleRemoveErrorMark = () => {
		removeErrorMark(boxInfo.hdu_id || '')
		setErrorTextShow(false)
		setErrorText('')
	}
	/**展示名称 */
	const boxMTShowByData = () => {
		let result: any = convertMsg(boxInfo, index) // 通过covertMSg处理数据
		if (!result) return
		if (result.type !== 0 && !(result.type === 9 && meetingType === 1)) {
			return (
				<>
					{!!result.stream && (
						<>
							<div className="name-ellipsis">{result.name}</div>
							{result.mtName && <div className="name-ellipsis">{result.mtName}</div>}
							<div className="name-ellipsis">{stream_position}</div>
						</>
					)}
					{!result.stream && (
						<>
							<div className="name-ellipsis">{result.name}</div>
							{result.mtName && <div className="name-ellipsis">{result.mtName}</div>}
						</>
					)}
				</>
			)
		} else {
			return <AddIcon></AddIcon>
		}
	}
	/**判断是数据框是否是可拖拽状态 */
	const isHasCannel = (item: TvWallMemberItemEntity) => {
		if (item.is_mine /**属于我的*/) {
			return true
		} else if (item.hdu_alias === '' /**未设置通道*/) {
			return false
		} else if (!item.is_online /**HDU不在线*/) {
			return false
		} else {
			if (item.is_used === 1 /**被占用 */) {
				return false
			} else if (item.is_used === 255 /**无效状态 */) {
				return false
			} else {
				return true
			}
		}
	}
	const handleDrop = (sourceData: DropData) => {
		const _source_data = sourceData.data?.mt /**拖拽进入终端的数据*/
		if (_source_data) {
			/**操作的对象以及位置(hdu_id可能不存在，不要采用hdu_id确定数据位置) 最好方式就是在此处进行操作对象和操作位置进行赋值*/
			update({ operateBoxInfo: boxInfo, operateBoxInfoIndex: index })
			/**多流 占三格*/
			if (_source_data.isMt && _source_data.stream) {
				let styleArr: { placeholder: string; data: any }[] = []
				for (let i = 0; i < boxDetailVOsSource.length; i++) {
					const current = boxDetailVOsSource[i] /**当前的盒子对象*/
					const flag = isHasCannel(current)

					if (flag) {
						/**证明可以放置终端 */
						if (
							current &&
							((current.member_type !== 0 && current.member_type !== 1) ||
								(current.member_type === 1 && current.mt_id != undefined))
						) {
							/**终端已存在 */
							styleArr.push({
								placeholder: 'fill',
								data: current,
							})
						} else {
							styleArr.push({
								placeholder: 'empty',
								data: null,
							})
						}
					} else {
						/**证明当前hdu_id对应异常 */
						styleArr.push({
							placeholder: 'broken',
							data: null,
						})
					}
				}
				getMTChnInfo(_source_data, (list) => {
					//有3格连续空,或者替换了多流，或者替换后正好3格连续空
					let mtchnids = list.map((x) => x.v_snd_chn_id).sort((a: number, b: number) => a - b)
					let checkoutArr = checkoutDomArr(styleArr, index, boxInfo, mtchnids)
					if (checkoutArr) {
						checkoutArr.forEach((sourcePlaceHolder, sourcePlaceHolderIndex) => {
							/**先找到书序对应的mt_chn_id sourcePlaceHolder之前是指盒子现在指位置*/
							let mtchnid =
								mtchnids[sourcePlaceHolderIndex] != undefined
									? Number(mtchnids[sourcePlaceHolderIndex])
									: 1
							const _members = boxDetailVOsSource
								.map((_item, _index) => {
									if (sourcePlaceHolder === _index) {
										let _mt = makeMtEntityParam(_source_data)
										return {
											..._mt,
											member_type: 1,
											hdu_id: _item.hdu_id,
											mt_id: _source_data.mt_id,
											mt_chn_id: mtchnid,
										}
									}
									return null
								})
								.filter(Boolean)
							const params = {
								mode: 1,
								show_mt_name: show_mt_name,
								batch_poll: null,
								members: _members,
							}
							/**更改通道 */
							changeTVWallChannel(params)
						})
					} else {
						Alert(t('电视墙通道资源不足'))
					}
				})
			} else {
				/**先找到对应的mt_chn_id*/
				const _members = boxDetailVOsSource
					.map((item, index) => {
						if (item.hdu_id === boxInfo.hdu_id) {
							let _mt = makeMtEntityParam(_source_data)
							return {
								..._mt,
								member_type: 1,
								hdu_id: boxInfo.hdu_id,
							}
						}
						return null
					})
					.filter(Boolean)
				const params = {
					mode: 1,
					show_mt_name: show_mt_name,
					batch_poll: null,
					members: _members,
				}
				/**更改通道 */
				changeTVWallChannel(params)
				//非多流，但是替换到了多流
				removeStreamDom()
			}
		}
	}
	const checkoutDomArr = (
		styleArr: Array<{ placeholder: string; data: any }>,
		currentIndex: number,
		_boxInfo: TvWallMemberItemEntity,
		mtchnIds: Array<number>
	) => {
		// console.log(t('Arguments=checkoutDomArr参数'), styleArr, currentIndex, _boxInfo, mtchnIds)
		///替换到了多流，优先级最高
		if (styleArr[currentIndex].placeholder === 'fill') {
			let { member_type, mt_id, stream, mt_key } = styleArr[currentIndex].data /**当前的有数据的盒子携带的信息 */
			if (member_type === 1 && mt_id && stream === 1) {
				let _arr = [
					styleArr[currentIndex - 2],
					styleArr[currentIndex - 1],
					styleArr[currentIndex],
					styleArr[currentIndex + 1],
					styleArr[currentIndex + 2],
				]
				let _res = []
				for (let i = 0; i < _arr.length; i++) {
					let item = _arr[i]
					if (item) {
						if (item.placeholder === 'empty') {
							_res.push('empty')
							continue
						}
						if (item.placeholder === 'broken') {
							_res.push(null)
							continue
						}
						if (mt_key === streamDomData(item.data).mt_key) {
							//是同一个多流终端
							_res.push('replace')
							continue
						}
						_res.push(null)
					} else {
						_res.push(null)
					}
				}
				let _res1 = [_res[0], _res[1], _res[2]],
					_res2 = [_res[1], _res[2], _res[3]],
					_res3 = [_res[2], _res[3], _res[4]]
				if (_res1.filter((x) => x === 'replace').length === 3) {
					let ids = _arr.slice(0, 3).map((x) => x.data.mt_chn_id)
					if (isEqualMtchnids(ids, mtchnIds)) {
						return [currentIndex - 2, currentIndex - 1, currentIndex]
					}
				}
				if (_res2.filter((x) => x === 'replace').length === 3) {
					let ids = _arr.slice(1, 4).map((x) => x.data.mt_chn_id)
					if (isEqualMtchnids(ids, mtchnIds)) {
						return [currentIndex - 1, currentIndex, currentIndex + 1]
					}
				}
				if (_res3.filter((x) => x === 'replace').length === 3) {
					let ids = _arr.slice(2, 5).map((x) => x.data.mt_chn_id)
					if (isEqualMtchnids(ids, mtchnIds)) {
						return [currentIndex, currentIndex + 1, currentIndex + 2]
					}
				}
				if (_res3.filter((x) => x === 'replace').length === 2 && _res3.filter(Boolean).length === 3) {
					let ids = _arr.slice(2, 5).map((x) => (x && x.data ? x.data.mt_chn_id : null))
					if (isEqualMtchnids(ids, mtchnIds)) {
						return [currentIndex, currentIndex + 1, currentIndex + 2]
					}
				}
				if (_res2.filter((x) => x === 'replace').length === 2 && _res2.filter(Boolean).length === 3) {
					let ids = _arr.slice(1, 4).map((x) => (x && x.data ? x.data.mt_chn_id : null))
					if (isEqualMtchnids(ids, mtchnIds)) {
						return [currentIndex - 1, currentIndex, currentIndex + 1]
					}
				}
				if (_res1.filter((x) => x === 'replace').length === 2 && _res1.filter(Boolean).length === 3) {
					let ids = _arr.slice(0, 3).map((x) => (x && x.data ? x.data.mt_chn_id : null))
					if (isEqualMtchnids(ids, mtchnIds)) {
						return [currentIndex - 2, currentIndex - 1, currentIndex]
					}
				}
			}
		}
		let arr1 = [styleArr[currentIndex - 2], styleArr[currentIndex - 1], styleArr[currentIndex]].filter(Boolean),
			arr2 = [styleArr[currentIndex - 1], styleArr[currentIndex], styleArr[currentIndex + 1]].filter(Boolean),
			arr3 = [styleArr[currentIndex], styleArr[currentIndex + 1], styleArr[currentIndex + 2]].filter(Boolean)
		if (arr3.length === 3) {
			let _empty = [arr3[1], arr3[2]].filter((x) => x.placeholder === 'empty')
			if (_empty.length === 2) {
				//放至最前，后2格均为空
				return [currentIndex, currentIndex + 1, currentIndex + 2]
			}
		}
		if (arr2.length === 3) {
			let _empty = [arr2[0], arr2[2]].filter((x) => x.placeholder === 'empty')
			if (_empty.length === 2) {
				//放至中间，前后均为空
				return [currentIndex - 1, currentIndex, currentIndex + 1]
			}
		}
		if (arr1.length === 3) {
			let _empty = [arr1[0], arr1[1]].filter((x) => x.placeholder === 'empty')
			if (_empty.length === 2) {
				//放至最后，前2格均为空
				return [currentIndex - 2, currentIndex - 1, currentIndex]
			}
		}
		return null
	}
	return (
		<Wrap className={`tvwall-list-item ${active ? 'active' : ''}`}>
			<DragDropContextProvider>
				<Droppable
					onDrop={(dataTransfer) => {
						handleDrop(dataTransfer)
					}}
				>
					{(setDroppableRef) => (
						<StyledNormalWrap
							left={_left}
							top={_right}
							width={_width}
							height={_height}
							mode={mode}
							disabled={false}
							ref={setDroppableRef}
							onMouseEnter={() => {
								setIsShowSetting(true)
							}}
							onMouseLeave={() => {
								setIsShowSetting(false)
							}}
						>
							<div className="re-box-content">{boxMTShowByData()}</div>
							{/**错误码*/}
							{boxDetailVOsSourceErrorCode &&
								boxInfo.hdu_id &&
								boxDetailVOsSourceErrorCode[boxInfo.hdu_id] && (
									<div className="errorMark" onClick={handleShowErrorMark}>
										{err_text_show && (
											<div className="tv-box-net-error">
												{err_text}
												<div
													className="error-img"
													onClick={(e) => {
														e.stopPropagation()
														handleRemoveErrorMark()
													}}
												></div>
											</div>
										)}
									</div>
								)}
							{/**设置*/}
							{mode !== 2 && (
								<BoxSetting
									boxInfo={boxInfo}
									index={index}
									is_show_setting={is_show_setting}
									handleSetActive={(flag: boolean) => {
										setActive(flag)
									}}
								></BoxSetting>
							)}
						</StyledNormalWrap>
					)}
				</Droppable>
			</DragDropContextProvider>
		</Wrap>
	)
}
